package com.example.ai.service;

import com.example.ai.model.LoginRequest;
import com.example.ai.model.LoginResponse;
import com.example.ai.model.User;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 认证服务类，处理用户登录和token管理
 */
@Service
public class AuthService {
    
    // 模拟用户数据库（实际项目中应连接真实数据库）
    private final Map<String, User> userDatabase = new HashMap<>();
    
    // 存储有效的token和对应的用户
    private final Map<String, UserTokenInfo> tokenStore = new HashMap<>();
    
    // token过期时间（毫秒）
    private static final long TOKEN_EXPIRATION_MS = TimeUnit.HOURS.toMillis(24);
    
    public AuthService() {
        // 初始化一些模拟用户数据
        userDatabase.put("user1", new User("user1", "password123"));
        userDatabase.put("admin", new User("admin", "admin123"));
        userDatabase.get("admin").setRole("ADMIN");
    }
    
    /**
     * 用户登录认证
     */
    public LoginResponse login(LoginRequest request) {
        LoginResponse response = new LoginResponse();
        
        // 验证请求参数
        if (request == null || request.getUsername() == null || request.getPassword() == null) {
            response.setSuccess(false);
            response.setMessage("用户名和密码不能为空");
            return response;
        }
        
        // 检查用户是否存在
        User user = userDatabase.get(request.getUsername());
        if (user == null || !user.getPassword().equals(request.getPassword())) {
            response.setSuccess(false);
            response.setMessage("用户名或密码错误");
            return response;
        }
        
        // 生成token
        String token = generateToken();
        Date expireTime = new Date(System.currentTimeMillis() + TOKEN_EXPIRATION_MS);
        
        // 存储token信息
        tokenStore.put(token, new UserTokenInfo(user, expireTime));
        
        // 设置响应信息
        response.setSuccess(true);
        response.setMessage("登录成功");
        response.setToken(token);
        response.setExpireTime(expireTime);
        response.setUser(user);
        
        return response;
    }
    
    /**
     * 验证token是否有效
     */
    public boolean validateToken(String token) {
        if (token == null || token.isEmpty()) {
            return false;
        }
        
        UserTokenInfo tokenInfo = tokenStore.get(token);
        if (tokenInfo == null) {
            return false;
        }
        
        // 检查token是否过期
        if (tokenInfo.getExpireTime().before(new Date())) {
            // 清理过期token
            tokenStore.remove(token);
            return false;
        }
        
        return true;
    }
    
    /**
     * 根据token获取用户信息
     */
    public User getUserByToken(String token) {
        if (!validateToken(token)) {
            return null;
        }
        
        return tokenStore.get(token).getUser();
    }
    
    /**
     * 生成随机token
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    
    /**
     * 用户token信息内部类
     */
    private static class UserTokenInfo {
        private final User user;
        private final Date expireTime;
        
        public UserTokenInfo(User user, Date expireTime) {
            this.user = user;
            this.expireTime = expireTime;
        }
        
        public User getUser() {
            return user;
        }
        
        public Date getExpireTime() {
            return expireTime;
        }
    }
}